package com.hexb.core.mybatis

import com.hexb.core.mybatis.entry.SqlEntry
import org.apache.ibatis.mapping.MappedStatement
import org.apache.ibatis.mapping.SqlCommandType
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
import org.apache.ibatis.session.Configuration
import org.apache.log4j.Logger

import java.lang.reflect.Array

/**
 * @Package : com.hexb.core.mybatis
 * @Author : hexb 
 * @Date : 2018-08-12 17:56
 */
class SQLDeleteBuilder {

    static final Logger logger = Logger.getLogger(SQLDeleteBuilder.class)
    static final String delete = 'delete'
    static final String deleteBatch = 'deleteBatch'

    static MappedStatement delete(SqlEntry entry, Configuration configuration) {
        buildDelete("${entry.namespace}.$delete", entry, configuration, false)
    }

    static MappedStatement deleteBatch(SqlEntry entry, Configuration configuration) {
        buildDelete("${entry.namespace}.$deleteBatch", entry, configuration, true)
    }

    static MappedStatement buildDelete(String id, SqlEntry entry, Configuration configuration, Boolean batch) {
        try {
            def sql = ["DELETE FROM ${entry.tableName} ", where(entry, batch)].join(' ')
            Class<?> clazz = batch ? Array.class : entry.idClass
            def sqlSource = new XMLLanguageDriver().createSqlSource(configuration, "<script>${sql}</script>", clazz)
            def msBuilder = new MappedStatement.Builder(configuration, id,
                    sqlSource,
                    SqlCommandType.UPDATE)
            msBuilder.build()
        } catch (e) {
            logger.error(e)
            throw e
        }
    }

    static String where(SqlEntry entry, Boolean batch) {
        !batch ? "WHERE `${entry.idEntry.column}`=#{_parameter}" :
                """WHERE `${entry.idEntry.column}` in
            <foreach collection="array" separator="," item="item" open="(" close=")">
                #{item}
            </foreach>
        """
    }
}
